package cn.com.wind.bdg.inmysql.inmysql.service;

import org.elasticsearch.action.admin.indices.create.CreateIndexResponse;
import org.elasticsearch.action.admin.indices.mapping.put.PutMappingRequest;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.search.SearchType;
import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.client.Client;
import org.elasticsearch.client.Requests;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import cn.com.wind.bdg.inmysql.inmysql.entity.Info;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class ESServiceImpl implements ESService {
    @Autowired
    private Client client;

    @Override
    public void query(String index, String type,String id) {
        SearchResponse response = client.prepareSearch(index).setTypes(type)
                .setSearchType(SearchType.QUERY_AND_FETCH)
                .setQuery(QueryBuilders.boolQuery()
                        .must(QueryBuilders.wildcardQuery("id",id)))
                .setFrom(0).setSize(10).setExplain(true).get();

        SearchHits hits = response.getHits();
        System.out.println(hits.getHits().length);
        SearchHit[] innerHits = hits.getHits();
        Map map = new HashMap<String, String>();
        for(SearchHit hit :innerHits){
            // ID 为hit.getId();
            Map<String, Object> source = hit.getSource();
            for(Map.Entry<String,Object> filed :source.entrySet()){
                String key = filed.getKey();
                String value = (String) filed.getValue();
                System.out.println("key===="+key+"    value====="+filed.getValue().toString());
                map.put(key,value);
            }
        }
//        redisService.hmset("21732"+id, map);
    }


    @Override
    public void add(String index, String type, Info info) throws Exception{
        // 使用XContentBuilder创建一个doc source
        XContentBuilder builder = XContentFactory.jsonBuilder()
                .startObject()
                .field("planting_district_code", info.getPLANTING_DISTRICT_CODE())
                .field("company_name", info.getCOMPANY_NAME())
                .field("planting_varieties", info.getPLANTING_VARIETIES())
                .field("registered_address", info.getREGISTERED_ADDRESS())
                .field("planting_district", info.getPLANTING_DISTRICT())
                .endObject();
        // setId(id)
        // 如果没有设置id，则ES会自动生成一个id setSource
        IndexResponse indexResponse = client.prepareIndex()
                .setIndex(index)
                .setType(type)
                .setId(info.getCOMPANY_NAME())
                .setSource(builder.string())
                .get();
        System.out.println("add成功");
    }

//    public void update(String index, String type, PersonData personData) throws Exception{
//        XContentBuilder builder = XContentFactory.jsonBuilder()
//                .startObject()
//                .field("code", personData.getCode())
//                .field("name", personData.getName())
//                .field("age", personData.getAge())
//                .field("hobby", personData.getHobby())
//                .endObject();
//        UpdateResponse updateResponse = client.prepareUpdate(index, type, String.valueOf(personData.getCode()))
//                .setDoc(builder).get();
//    }
    @Override
    public void delete(String index, String type, String id)  throws Exception{
        DeleteResponse deleteResponse =client
                .prepareDelete()
                .setIndex(index)
                .setType(type)
                .setId(id)
                .get();
    }

    //创建索引库
    public void createIndex(String index){
        CreateIndexResponse createIndexResponse = client.admin().indices().prepareCreate(index).get();
        System.out.println(createIndexResponse.isAcknowledged()); // true表示成功
    }

    //给索引库增加 type,mapping
    public void addMapping(String index,String type) throws Exception{
        // 使用XContentBuilder创建Mapping
        XContentBuilder builder =
                XContentFactory.jsonBuilder()
                        .startObject()
                        .field("properties")
                        .startObject()
                        .field("id")
                        .startObject()
                        .field("type", "string")
                        .endObject()
                        .field("title")
                        .startObject()
//                        .field("analyzer", "standard")
                        .field("type", "string")
                        .endObject()
                        .field("time")
                        .startObject()
                        .field("type", "string")
                        .endObject()
                        .field("content")
                        .startObject()
//                        .field("analyzer", "standard")
                        .field("type", "string")
                        .endObject()
                        .endObject();
        System.out.println(builder.string());
        PutMappingRequest mappingRequest = Requests.putMappingRequest(index).source(builder).type(type);
        client.admin().indices().putMapping(mappingRequest).actionGet();
    }

}
